package com.broada.apm.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.ajax.ConfigResult;
import com.broada.apm.base.BaseService;
import com.broada.apm.common.util.CsvParserUtil;
import com.broada.apm.common.util.ZipUtil;
import com.broada.apm.entity.ConfigVariable;
import com.broada.apm.entity.IPLocation;
import com.broada.apm.entity.NoticeCommandException;
import com.broada.apm.entity.ThresholdType;
import com.broada.apm.entity.UserInfo;
import com.broada.apm.es.bean.ClusterInfo;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.indicator.api.common.IllegalIPAddressException;
import com.broada.apm.model.ConfigItem;
import com.broada.apm.model.Dimension.Area;
import com.broada.apm.model.Dimension.Error;
import com.broada.apm.model.L7Module;
import com.broada.apm.model.PagingList;
import com.broada.apm.model.User;
import com.broada.apm.mysql.handler.IpLocationsImporter;
import com.broada.apm.protocol.L7ModuleManager;
import com.broada.apm.service.ConfigService;
import com.broada.apm.util.JsonUtil;
import com.broada.apm.util.SettingMapConstants;
import com.broada.apm.util.TokenManager;
import com.broada.apm.utils.ApmFileUtils;
import com.broada.apm.utils.ExceptionUtils;
import com.google.common.base.Strings;

/**
 * 
 * 系统配置操作service接口实现类
 * 
 * @author xiangsy Create By 2015年2月6日 上午10:16:59
 */
public class ConfigServiceImpl extends BaseService implements ConfigService {
	private Logger log = LoggerFactory.getLogger(ConfigServiceImpl.class);

	@Override
	public ConfigResult addBasicCon(ConfigVariable variable) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.addConfigData(variable);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage("保存配置失败");
			ExceptionUtils.error(log, "保存配置失败:", e);
		} catch (NoticeCommandException e) {
			result.setFailMessage("通知Indicator模块异常");
			ExceptionUtils.error(log, "通知Indicator模块异常", e);
		}
		return result;
	}

	@Override
	public ConfigResult queryBasicCon(String confItem) {
		ConfigResult result = new ConfigResult();
		List<ConfigItem> settings = null;
		try {
			settings = confLogic.queryConfigData(confItem);
			result.setConfigData(SettingMapConstants.toMap(settings));
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
			log.error("查询配置失败", e);
		}
		return result;
	}

	@Override
	public ConfigResult getSysTime() {
		Date date = Calendar.getInstance().getTime();
		String dateStr = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss  E").format(date);
		ConfigResult result = new ConfigResult();
		result.setNowTime(dateStr);
		return result;
	}

	@Override
	public ConfigResult queryAreaList(String areaCode) {
		ConfigResult result = new ConfigResult();
		List<Area> areas = confLogic.queryAreaByCode(areaCode);
		result.setArea(areas);
		return result;
	}

	@Override
	public ConfigResult updateLib() {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.updateLib();
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, "内置库立即更新失败:", e);
		}
		return result;
	}

	@Override
	public ConfigResult addIpRepair(IPLocation obj) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.saveIPLocation(obj);
		} catch (NoticeCommandException e) {
			ExceptionUtils.error(log, "通知Indicator模块异常", e);
			result.setFailMessage("通知Indicator模块异常");
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(log, "保存Ip地址失败", e);
			result.setFailMessage("保存Ip地址失败");
		} catch (IllegalIPAddressException e) {
			ExceptionUtils.error(log, e.getMessage(), e);
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult updIpRepair(IPLocation obj) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.saveIPLocation(obj);
		} catch (NoticeCommandException e) {
			ExceptionUtils.error(log, "通知Indicator模块异常", e);
			result.setFailMessage("通知Indicator模块异常");
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(log, "保存Ip地址失败", e);
			result.setFailMessage("保存Ip地址失败");
		} catch (IllegalIPAddressException e) {
			ExceptionUtils.error(log, e.getMessage(), e);
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult queryIpRepair(String ip, String areaCode, String memo, String pageIndex, String pageSize) {
		ConfigResult result = new ConfigResult();
		List<IPLocation> locations = new ArrayList<IPLocation>();
		try {
			locations = confLogic.queryIPLocation(ip, areaCode, memo, (pageIndex == null ? "0" : pageIndex), (pageSize == null ? "10" : pageSize));
			result.put("pageIndex", pageIndex == null ? 0 : pageIndex);
			result.put("pageSize", pageSize == null ? 10 : pageSize);
			result.put("total", confLogic.queryAllIPLocationSize());
			result.setIpAreas(locations);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, "查询IP地理位置库维护列表失败", e);
		}
		return result;
	}

	@Override
	public ConfigResult delIpRepair(String IpareaIndex) {
		ConfigResult result = new ConfigResult();
		if (Strings.isNullOrEmpty(IpareaIndex)) {
			result.setFailMessage("id为空！");
			return result;
		}
		try {
			confLogic.deleteIPLocation(IpareaIndex);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, e.getMessage(), e);
		} catch (NoticeCommandException e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, e.getMessage(), e);
		}
		return result;
	}

	@Override
	public ConfigResult queryUser(int pageIndex, int pageSize) {
		ConfigResult result = new ConfigResult();
		PagingList<User> users = null;
		try {
			users = confLogic.queryUser(pageIndex, pageSize);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
		}
		result.addPagingList(users);
		return result;
	}

	@Override
	public ConfigResult addUser(String json) {
		ConfigResult result = new ConfigResult();
		try {
			User user = JsonUtil.getInstance().json2Obj(json, User.class);
			confLogic.addUser(user);
		} catch (Exception e) {
			result.setInvalidMessage(e.getMessage());
			ExceptionUtils.error(log, "用户添加失败:", e);
		}
		return result;
	}

	@Override
	public ConfigResult updateUser(String json) {
		ConfigResult result = new ConfigResult();
		try {
			User user = JsonUtil.getInstance().json2Obj(json, User.class);
			confLogic.updateUser(user);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, "用户修改失败:", e);
		}
		return result;
	}

	@Override
	public ConfigResult delUser(String userId) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.delUser(userId);
		} catch (ApmDataIndicatorException e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, "用户删除失败:", e);
		}
		return result;
	}

	@Override
	public ConfigResult updatePwd(String token, UserInfo user) {
		ConfigResult result = new ConfigResult();
		String oldPass = user.getOldPass();
		String newPass = user.getNewPass();
		String userId = user.getUserId();
		if (StringUtils.isBlank(userId)) {
			// 拿到解密数据
			try {
				userId = TokenManager.getUser(token).getId();
			} catch (Exception e) {
				result.setFailMessage("密码修改失败!");
				ExceptionUtils.error(log, "密码修改失败!", e);
				return result;
			}
		}
		if (StringUtils.isBlank(userId)){
			result.setFailMessage("参数错误，userId为空");
			return result;
		}
		try {
			confLogic.updatePwd(userId, oldPass, newPass);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
			ExceptionUtils.error(log, "密码修改失败!", e);
		}
		return result;
	}

	@Override
	public ConfigResult updateStatus(User user) {
		ConfigResult result = new ConfigResult();
		String userId = user.getId();
		int status = user.getStatus();
		try {
			confLogic.updateStatus(userId, status);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult queryL7Module() {
		ConfigResult result = new ConfigResult();
		List<L7Module> modules = confLogic.queryL7Module();
		result.setModules(modules);
		return result;
	}

	@Override
	public ConfigResult deleteL7Module(String moduleId) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.deleteL7Module(moduleId);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@Override
	public ConfigResult updStatusL7Module(L7Module module) {
		ConfigResult result = new ConfigResult();
		try {
			String moduleId = module.getId();
			int status = module.getStatus();
			confLogic.updStatusL7Module(moduleId, status);
		} catch (Exception e) {
			ExceptionUtils.error(log, "模块状态更新失败.", e);
			result.setFailMessage("模块状态更新失败.");
		}
		return result;
	}

	@Override
	public ConfigResult setL7ModuleCode(Error error) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.setL7ModuleCode(error);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult addL7ModuleCode(Error error) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.addL7ModuleCode(error);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult queryL7ModuleCode(String moduleId) {
		ConfigResult result = new ConfigResult();
		try {
			List<Error> listError = confLogic.queryL7ModuleCode(moduleId);
			result.setCodeArr(listError);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult delL7ModuleCode(int protocol, String id, String code, String errorMessage) {
		ConfigResult result = new ConfigResult();
		try {
			confLogic.delL7ModuleCode(protocol, id, code, errorMessage);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult historyDiskData() {
		ConfigResult result = new ConfigResult();
		try {
			ClusterInfo cluster = confLogic.historyDiskData();
			result.setDiskData(cluster);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
		}
		return result;

	}

	@Override
	public ConfigResult historyCleanData(int cleantime, String appIds) {
		ConfigResult result = new ConfigResult();
		if (!confLogic.historyCleanData(cleantime, appIds))
			result.setFailMessage("清除应用系统性能数据失败...");
		return result;
	}

	@Override
	public ConfigResult queryAlertThresholdType() {
		ConfigResult result = new ConfigResult();
		List<ThresholdType> thresholds = confLogic.queryAlertThresholdType();
		result.setThresholds(thresholds);
		return result;
	}

	@Override
	public ConfigResult uploadL7Module(HttpServletRequest request, HttpServletResponse response) {
		ConfigResult result = new ConfigResult();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			DiskFileItemFactory df = new DiskFileItemFactory();
			// 设定阀值1M，如果超过这个值，则文件就直接写到临时文件，不会一直占用内存
			// 利用这个特性可在上传大文件的时候不会占用大量内存，可以提高并发使用量。
			df.setSizeThreshold(1024 * 1024);
			File tempFile = FileUtils.getTempDirectory();
			if (!tempFile.exists())
				tempFile.mkdirs();

			String tempPath = tempFile.getAbsolutePath();
			df.setRepository(tempFile);
			ServletFileUpload sf = new ServletFileUpload(df);
			sf.setFileSizeMax(1024 * 1024 * 100);// 上传文件最大为100M
			@SuppressWarnings("unchecked")
			List<FileItem> list = sf.parseRequest(request);

			for (int i = 0; i < list.size(); i++) {
				FileItem fileItem = (FileItem) list.get(i);
				String fileName = fileItem.getName();
				// 文件后缀格式检查
				if (fileName == null || "".equals(fileName.trim())) {
					out.println("<script>parent.APM.iframeCallback(1);</script>");
				} else {
					boolean isRealType = false;
					String curfileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					// System.out.println("文件後綴名:" + curfileEnd);
					if (curfileEnd != null && !"".equals(curfileEnd.trim())) {
						if ("mod".equals(curfileEnd))
							isRealType = true;
					}
					if (!isRealType) {
						// 提示错误信息:文件格式不正确
						out.println("<script>parent.APM.iframeCallback(2);</script>");
					} else {
						// 写入临时文件
						File f2 = new File(tempPath, fileName);
						fileItem.write(f2);
						int status = confLogic.resolveL7Module(f2);
						// L7module存在且运行中 提示先禁止模块。
						if (status == 0)
							out.println("<script>parent.APM.iframeCallback(3);</script>");
						// L7module已经存在
						if (status == 1)
							out.println("<script>parent.APM.iframeCallback(4);</script>");
						if (status == 2)
							out.println("<script>parent.APM.iframeCallback(5);</script>");
						if (status == 6)
							out.println("<script>parent.APM.iframeCallback(6,'请先添加同步模块：1.mod');</script>");
					}
				}
			}

		} catch (Exception e) {
			ExceptionUtils.error(log,"模块上传失败！" , e);
			out.println("<script>parent.APM.iframeCallback(6,'" + e.getMessage() + "');</script>");
			result.setFailMessage("模块上传失败！");
		} finally {
			out.flush();
			out.close();
		}
		return result;
	}

	@Override
	public ConfigResult downloadL7Module(HttpServletRequest request, HttpServletResponse response, String moduleName,
			int l7_proto) {
		ConfigResult result = new ConfigResult();
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		FileInputStream fis = null;
		BufferedInputStream buff = null;
		OutputStream myout = null;
		try {
			String fileName = java.net.URLDecoder.decode(moduleName, "utf-8");
			File file = L7ModuleManager.exportL7Module(l7_proto, fileName);
			// 设置response的编码方式
			response.setContentType("application/x-msdownload");
			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());
			// 设置附加文件名(解决中文乱码)
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(file.getName().getBytes("gbk"), "iso-8859-1"));
			fis = new FileInputStream(file);
			buff = new BufferedInputStream(fis);
			byte[] b = new byte[1024];// 相当于我们的缓存
			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 从response对象中得到输出流,准备下载
			myout = response.getOutputStream();
			while (k < file.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}
			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();
		} catch (Exception e) {
			log.error("文件下载失败！" + e.getMessage());
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (buff != null)
					buff.close();
				if (myout != null)
					myout.close();
			} catch (Exception e) {
				ExceptionUtils.error(log, "导出L7模块出错", e);
				result.setFailMessage("导出L7模块出错");
			}
		}
		return result;
	}

	@Override
	public ConfigResult LogoUpload(HttpServletRequest request, HttpServletResponse response) {
		ConfigResult result = new ConfigResult();
		// 最大文件上传大小为10M
		int fileMaxSiz = 10 * 1024 * 1024;
		// 文件后缀名限制
		// String fileEnd="jpg,png,bmp,ico,gif";
		String fileEnd = "png";
		// 存放的图片名称
		String picName = "logo.";
		// 出厂默认defaultlogo
		String defaultLogo = "default_logo.";
		// 文件上传存放路径设置
		String saveDir = "../webapps/web/apps/main/img/";
		PrintWriter out = null;
		boolean Ifapdex = false;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				File f = ApmFileUtils.getAbsoluteFile(FileUtils.getTempDirectory().getAbsolutePath());
				factory.setRepository(f);// 指定上传文件的临时目录
				factory.setSizeThreshold(1024 * 1024);// 指定在内存中缓存数据大小,单位为byte

				ServletFileUpload upload = new ServletFileUpload(factory);
				@SuppressWarnings("unchecked")
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = itr.next();
					if (item.isFormField()) {
						// 非文件类型值
						// System.out.println("表单参数名:" + item.getFieldName() + "，表单参数值:" +
						// item.getString("UTF-8"));
						String apdextmp = item.getFieldName();
						String apdex_t = "";
						if ("apdex_t".endsWith(apdextmp)) {
							apdex_t = item.getString("UTF-8");
							// 保存apdex值
							if (StringUtils.isNotEmpty(apdex_t)) {
								ConfigVariable variable = new ConfigVariable(1);
								variable.setApdex_t(apdex_t);
								confLogic.addConfigData(variable);
								Ifapdex = true;
							}
						}
					} else {
						if (item.getSize() > 0) {
							// System.out.println("上传文件的大小:" + item.getSize());
							// System.out.println("上传文件的类型:" + item.getContentType());
							// item.getName()返回上传文件在客户端的完整路径名称
							// System.out.println("上传文件的名称:" + item.getName());

							// 文件名
							String fileName = item.getName();
							// 文件后缀格式检查
							boolean isRealType = false;
							if (fileName != null && !fileName.equals("")) {
								String curfileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
								// System.out.println("文件後綴名:" + curfileEnd);
								if (curfileEnd != null && !"".equals(curfileEnd.trim())) {
									String[] arrType = fileEnd.split(",");
									for (String str : arrType) {
										if (curfileEnd.equals(str.toLowerCase())) {
											isRealType = true;
											break;
										}
									}
								}

								// 文件大小检查
								boolean isRealSize = false;
								if (item.getSize() < fileMaxSiz) {
									// 小于指定尺寸才允许上传
									isRealSize = true;
									upload.setFileSizeMax(fileMaxSiz);// 指定单个上传文件的最大尺寸
								}

								if (isRealType && isRealSize) {
									File srcFile = ApmFileUtils.getFile(saveDir + picName + curfileEnd);
									File destFile = ApmFileUtils.getFile(saveDir + defaultLogo + fileEnd);
									if (!destFile.exists()) {
										srcFile.renameTo(destFile);
									}
									File file = ApmFileUtils.getFile(saveDir + picName + curfileEnd);
									item.write(file);
									out.println("<script>parent.APM.iframeCallback(1);</script>");
								} else {
									if (!isRealType) {
										// 提示错误信息:文件格式不正确
										out.println("<script>parent.APM.iframeCallback(2);</script>");
									}
									if (!isRealSize) {
										// 提示错误信息:文件大小太大
										out.println("<script>parent.APM.iframeCallback(3);</script>");
									}
									if (!(isRealType || isRealSize)) {
										// 提示错误信息:文件太大,上传文件格式受限制
										out.println("<script>parent.APM.iframeCallback(4);</script>");
									}
								}
							} else {
								out.println("<script>parent.APM.iframeCallback(5);</script>");
							}
						} else {
							if (Ifapdex) {
								out.println("<script>parent.APM.iframeCallback(7);</script>");
							} else {
								out.println("<script>parent.APM.iframeCallback(8);</script>");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			out.println("<script>parent.APM.iframeCallback(6);</script>");
			log.error("logo上传失败,出现异常！", e.getMessage());
			result.setFailMessage("logo上传失败,出现异常！");
		}finally {
			out.flush();
			out.close();
		}
		return result;
	}

	@Override
	public ConfigResult ipFileUpload(HttpServletRequest request, HttpServletResponse response) {
		ConfigResult result = new ConfigResult();
		// 最大文件上传大小为50M
		int fileMaxSiz = 50 * 1024 * 1024;
		// 文件后缀名限制
		// String fileEnd="jpg,png,bmp,ico,gif";
		String fileEnd = "csv";
		// 存放的文件名称
		String picName = "IPLeadInMod.";
		// 文件上传存放路径设置
		String saveDir = "temp/";
		File saveFile = ApmFileUtils.getFile(saveDir);
		if (!saveFile.exists() && !saveFile.isDirectory()) {
			saveFile.mkdir();
		}
		PrintWriter out = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				File f = ApmFileUtils.getAbsoluteFile(FileUtils.getTempDirectory().getAbsolutePath());
				factory.setRepository(f);// 指定上传文件的临时目录
				factory.setSizeThreshold(1024 * 1024);// 指定在内存中缓存数据大小,单位为byte
				ServletFileUpload upload = new ServletFileUpload(factory);
				@SuppressWarnings("unchecked")
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = itr.next();
					if (!item.isFormField()) {
						if (item.getSize() > 0) {
							// System.out.println("上传文件的大小:" + item.getSize());
							// System.out.println("上传文件的类型:" + item.getContentType());
							// item.getName()返回上传文件在客户端的完整路径名称
							// System.out.println("上传文件的名称:" + item.getName());
							// 文件名
							String fileName = item.getName();
							// 文件后缀格式检查
							boolean isRealType = false;
							if (fileName != null && !fileName.equals("")) {
								String curfileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
								// System.out.println("文件後綴名:" + curfileEnd);
								if (curfileEnd != null && !"".equals(curfileEnd.trim())) {
									String[] arrType = fileEnd.split(",");
									for (String str : arrType) {
										if (curfileEnd.equals(str.toLowerCase())) {
											isRealType = true;
											break;
										}
									}
								}
								// 文件大小检查
								boolean isRealSize = false;
								if (item.getSize() < fileMaxSiz) {
									// 小于指定尺寸才允许上传
									isRealSize = true;
									upload.setFileSizeMax(fileMaxSiz);// 指定单个上传文件的最大尺寸
								}

								if (isRealType && isRealSize) {
									// 上传文件的保存路径
									File file = ApmFileUtils.getFile(saveDir + picName + curfileEnd);
									item.write(file);
									// 读入csv文件
									if (file.exists() && !file.isDirectory()) {
										String savfFile = saveDir + picName + curfileEnd;
										CsvParserUtil parser = new CsvParserUtil(savfFile);
										List<List<String>> lst = parser.readCSVFile();
										List<IPLocation> iplist = parser.listToIpObj(lst);
										int i = 0;
										if (iplist.size() > 0) {
											i = confLogic.ipFileUpload(iplist);
											if (i == 1) {
												out.println("<script>parent.APM.iframeCallback(1," + iplist.size() + ");</script>");
											} else {
												out.println("<script>parent.APM.iframeCallback(2,0);</script>");
											}
										} else {
											out.println("<script>parent.APM.iframeCallback(3,0);</script>");
										}
									}
								} else {
									if (!isRealType) {
										// 提示错误信息:文件格式不正确
										out.println("<script>parent.APM.iframeCallback(4,0,'');</script>");
									}
									if (!isRealSize) {
										// 提示错误信息:文件大小太大
										out.println("<script>parent.APM.iframeCallback(5,0,'');</script>");
									}
									if (!(isRealType || isRealSize)) {
										// 提示错误信息:文件太大,上传文件格式受限制
										out.println("<script>parent.APM.iframeCallback(6,0,'');</script>");
									}
								}
							} else {
								out.println("<script>parent.APM.iframeCallback(7,0,'');</script>");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			out.println("<script>parent.APM.iframeCallback(8,0,'" + e.getMessage() + "');</script>");
			log.error("文件上传失败,出现异常！", e.getMessage());
			result.setFailMessage("文件上传失败,出现异常！");
		}finally {
			out.flush();
			out.close();
		}
		return result;
	}

	@Override
	public ConfigResult queryBaseApdex() {
		ConfigResult result = new ConfigResult();
		result.setApdexT(confLogic.queryBaseApdex());
		return result;
	}

	@Override
	public ConfigResult currentUser(String token) {
		ConfigResult result = new ConfigResult();
		try {
			User user = TokenManager.getUser(token);
			result.setUser(user);
		} catch (Exception e) {
			result.setFailMessage(e.getMessage());
			log.error("当前用户查询失败!", e.getMessage());
		}
		return result;
	}

	@Override
	public ConfigResult innerLibUpload(HttpServletRequest request, HttpServletResponse response){
		ConfigResult result = new ConfigResult();
		// 最大文件上传大小为10M
		int fileMaxSiz = 50 * 1024 * 1024;
		// 文件后缀名限制
		String fileEnd = "zip";
		// 存放的图片名称
		String picName = "innerIPLib.";
		// 文件上传存放路径设置
		String saveDir ="../webapps/front/WEB-INF/database/";
		PrintWriter out = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				File f = ApmFileUtils.getAbsoluteFile(FileUtils.getTempDirectory().getAbsolutePath());
				factory.setRepository(f);// 指定上传文件的临时目录
				factory.setSizeThreshold(1024 * 1024);// 指定在内存中缓存数据大小,单位为byte

				ServletFileUpload upload = new ServletFileUpload(factory);
				@SuppressWarnings("unchecked")
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = itr.next();
					if (!item.isFormField()) {
						if (item.getSize() > 0) {
							// System.out.println("上传文件的大小:" + item.getSize());
							// System.out.println("上传文件的类型:" + item.getContentType());
							// item.getName()返回上传文件在客户端的完整路径名称
							// System.out.println("上传文件的名称:" + item.getName());

							// 文件名
							String fileName = item.getName();
							// 文件后缀格式检查
							boolean isRealType = false;
							if (fileName != null && !fileName.equals("")) {
								String curfileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
								// System.out.println("文件後綴名:" + curfileEnd);
								if (curfileEnd != null && !"".equals(curfileEnd.trim())) {
									String[] arrType = fileEnd.split(",");
									for (String str : arrType) {
										if (curfileEnd.equals(str.toLowerCase())) {
											isRealType = true;
											break;
										}
									}
								}

								// 文件大小检查
								boolean isRealSize = false;
								if (item.getSize() < fileMaxSiz) {
									// 小于指定尺寸才允许上传
									isRealSize = true;
									upload.setFileSizeMax(fileMaxSiz);// 指定单个上传文件的最大尺寸
								}

								if (isRealType && isRealSize) {
									// File tempFile = new File(item.getName());
									// 上传文件的保存路径
									// File file = new File(saveDir, tempFile.getName());
									File file = ApmFileUtils.getFile(saveDir + picName + curfileEnd);
									item.write(file);

									File map_dir = ApmFileUtils.createTempDirectory("apm_map");
									File ipdb_dir = ApmFileUtils.createTempDirectory("apm_ip_db");
									ZipUtil.unzip(ApmFileUtils.getFile(saveDir + "map-region.zip"), map_dir, false, true);
									ZipUtil.unzip(ApmFileUtils.getFile(saveDir + "innerIPLib.zip"), ipdb_dir, false, true);
									IpLocationsImporter.importFromFile(map_dir.listFiles()[0], ipdb_dir.listFiles()[0]);
									out.println("<script>parent.APM.iframeCallback(1);</script>");
								} else {
									if (!isRealType) {
										// 提示错误信息:文件格式不正确
										out.println("<script>parent.APM.iframeCallback(2);</script>");
									}
									if (!isRealSize) {
										// 提示错误信息:文件大小太大
										out.println("<script>parent.APM.iframeCallback(3);</script>");
									}
									if (!(isRealType || isRealSize)) {
										// 提示错误信息:文件太大,上传文件格式受限制
										out.println("<script>parent.APM.iframeCallback(4);</script>");
									}
								}
							} else {
								out.println("<script>parent.APM.iframeCallback(5);</script>");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			out.println("<script>parent.APM.iframeCallback(6);</script>");
			log.error("logo上传失败,出现异常！", e.getMessage());
			result.setFailMessage("logo上传失败,出现异常！");
		} finally {
			out.flush();
			out.close();
		}
		return result;
	}

	@Override
	public ConfigResult downloadIPLibMod(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ConfigResult result = new ConfigResult();
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		FileInputStream fis = null;
		BufferedInputStream buff = null;
		OutputStream myout = null;
		try {
			String saveDir = "../webapps/front/ipmodule/模板与地区编码表.zip";
			File file = ApmFileUtils.getFile(saveDir);
			// 设置response的编码方式
			response.setContentType("application/x-msdownload");
			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());
			// 设置附加文件名(解决中文乱码)
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(file.getName().getBytes("gbk"), "iso-8859-1"));
			fis = new FileInputStream(file);
			buff = new BufferedInputStream(fis);
			byte[] b = new byte[1024];// 相当于我们的缓存
			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 从response对象中得到输出流,准备下载
			myout = response.getOutputStream();
			while (k < file.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}
			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();
		} catch (Exception e) {
			log.error("文件下载失败！" + e.getMessage());
			result.setFailMessage("文件下载失败！");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (buff != null)
					buff.close();
				if (myout != null)
					myout.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

}
